import React from 'react';
import { connect } from 'dva';
import { Link } from 'dva/router';
import { List, Avatar, message, Icon, Modal } from 'antd';
import _ from 'lodash';
import EditModal from './edit';

import FatherImg from '../../assets/warehouse_father.png';
import ChildImg from '../../assets/warehouse_child.png';

const style = require('../app.less');
const styles = require('./index.less');

const ListContent = ({ place, capacity, contact, typeName }) => (
  <div className={styles.listContent}>
    <div className={styles.listContentItem} style={{ width: 150 }}>
      <span>地址</span>
      <p>{place}</p>
    </div>
    <div className={styles.listContentItem}>
      <span>容量</span>
      <p>{capacity}</p>
    </div>
    <div className={styles.listContentItem}>
      <span>联系方式</span>
      <p>{contact}</p>
    </div>
    <div className={styles.listContentItem}>
      <span>类型</span>
      <p>{typeName}</p>
    </div>
  </div>
);

/**
 * 扁平化warehouse
 *
 * @param {*} warehouse
 *  {
 *      warehouse: Object,
 *      children: []
 *   }
 */
const flatten = (warehouse) => {
  if (!warehouse) {
    return [];
  }
  const result = [];
  result.push(_.cloneDeep(warehouse.warehouse));
  result[0].isFather = true;
  warehouse.children.forEach((i) => {
    const item = _.cloneDeep(i);
    item.warehouse.children = item.children;
    result.push(item.warehouse);
  });
  return result;
};

class Warehouse extends React.Component {
  constructor(p) {
    super(p);
    this.seeChildren = this.seeChildren.bind(this);
    this.onEditFinish = this.onEditFinish.bind(this);
    this.back = this.back.bind(this);
    this.edit = this.edit.bind(this);

    this.state = {
      prev: [],
      current: null,
      modelVisible: false,
      editItem: null,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'warehouse/queryChild',
      payload: {
        onEnd: (err, warehouse) => {
          if (err) {
            return message.error(err);
          }
          this.setState({
            current: warehouse,
            top: warehouse,
          });
        },
      },
    });
  }

   // 处理编辑结束后的事件
  onEditFinish() {
    this.setState({
      modelVisible: false,
      editItem: null,
    }, () => {
      // 重新载入数据
      this.componentDidMount();
    });
  }

  /**
   * 查看子库
   * @param {String} wid
   */
  seeChildren(wid) {
    return () => {
      const select = _.get(this, 'state.current.children').find(item => item.warehouse.wid === wid);
      this.state.prev.push(this.state.current);
      this.state.current = select;
      this.setState({});
    };
  }

  /**
   * 返回上一层子库
   */
  back() {
    if (this.state.prev.length === 0) {
      message.error('已到顶层');
      return;
    }
    this.state.current = this.state.prev.pop();
    this.setState({});
  }

  /**
   * 监听编辑按钮
   *
   * @param {*} item 需要被编辑的仓库
   */
  edit(item) {
    return () => {
      this.setState({
        modelVisible: true,
        editItem: item,
      });
    };
  }

  render() {
    const { current, prev, modelVisible, editItem } = this.state;
    const { loading, warehouse } = this.props;
    const { defaultWid } = warehouse;
    return (
      <div className={style.container}>
        {
          modelVisible && <EditModal
            data={editItem}
            onFinish={this.onEditFinish}
            visible={modelVisible}
          />
        }
        <div className={styles.container}>
          <br />
          <h2>仓库列表</h2>
          {
            prev.length !== 0 && (
              <a
                onClick={this.back}
                style={{
                  margin: '10px 0',
                  display: 'block',
                }}
              >
                <Icon type="double-left" />返回上一层
            </a>
            )
          }
          <List
            loading={loading.effects['warehouse/queryChild']}
            itemLayout="horizontal"
            dataSource={flatten(current)}
            renderItem={(item) => {
              const actions = [
                <Link to={`/warehouse_location?wid=${item.wid}`}>查看</Link>,
              ];

              if (String(item.wid) === String(defaultWid)) {
                actions.push(<Link onClick={this.edit(item)}>编辑</Link>);
              }

              if (_.get(item, 'children.length')) {
                actions.push(<a onClick={this.seeChildren(item.wid)}>子库</a>);
              }

              // 为了美观而填充的空格，没有什么作用
              if (actions.length === 1) {
                actions.push(<a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>);
              }

              const title = `${item.thename}${String(item.wid) === String(defaultWid) ? '(我的仓库)' : ''}`;

              return (
                <List.Item className={styles.item} actions={actions}>
                  <List.Item.Meta
                    avatar={<Avatar src={item.isFather ? FatherImg : ChildImg} />}
                    title={<Link to={`/warehouse_location?wid=${item.wid}`}>{title}</Link>}
                    description={item.remark}
                  />
                  <ListContent
                    place={item.place}
                    capacity={item.capacity}
                    contact={item.contact}
                    typeName={item.typeName}
                  />
                </List.Item>
              );
            }
          }
          />
        </div>
      </div>
    );
  }
}

export default connect(state => state)(Warehouse);
